package com.imageim.yimirror.common.ui.drawbody;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.common.util.SoundUtil;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;

import java.lang.ref.WeakReference;

/**
 * Created by Bruce.Zhou on 2018/10/8 16:29.
 * Email: 907160968@qq.com
 */
public class BodyRectViewForMem extends RelativeLayout {
    public BodyRectViewForMem(Context context) {
        super(context);
        init();
    }

    public BodyRectViewForMem(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BodyRectViewForMem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private static final int MSG_TIP_TEXT = 1;
    private static final int MSG_TIMER_COUNT = 2;
    //    private static final int MSG_PROGRESS = 3;
    private String tipText = "请站入虚线框内拍照";
    private ImageView ivStandardRect;
    private ImageView ivKedu;
    private LinearLayout panelStandTip;
    private ImageView ivNeck;
    private ImageView ivYaoshen;
    private ImageView ivLegLong;
    private ImageView ivSmallLeg;
    private TextView tvStandTip;
    private View btnStartTimer;
    //    private View panelStartTipText;
    private View panelTimerProgress;
    private TextView tvCount;
    //    private ProgressBar progressBar;
    private ImageView ivDotLineX;
    private ImageView ivDotLineY;

    private int count = 5;
    private int wordNum = 1;
    private int progress = 0;
    private MyHandler myHandler;

    public interface OnTimeCountOverListener {
        void onTimeOver();
    }

    private OnTimeCountOverListener onTimeCountOverListener;

    public void setOnTimeCountOverListener(OnTimeCountOverListener onTimeCountOverListener) {
        this.onTimeCountOverListener = onTimeCountOverListener;
    }

    private int[] soundResIds = new int[]{
            R.raw.t1, R.raw.t2, R.raw.t3, R.raw.t4, R.raw.t5
    };

    public static class MyHandler extends Handler {
        private WeakReference<BodyRectViewForMem> reference;

        public MyHandler(BodyRectViewForMem bodyRectView) {
            reference = new WeakReference<>(bodyRectView);
        }

        @Override
        public void handleMessage(Message msg) {
            if (reference == null) {
                return;
            }
            BodyRectViewForMem bodyRectView = reference.get();
            if (bodyRectView != null) {
                switch (msg.what) {
                    case MSG_TIP_TEXT:
                        removeMessages(MSG_TIP_TEXT);
                        bodyRectView.tvStandTip.setText(bodyRectView.tipText.substring(0, bodyRectView.wordNum));
                        if (bodyRectView.wordNum < bodyRectView.tipText.length()) {
                            bodyRectView.wordNum++;
                            // 显示下一个
                            Message nextMsg = Message.obtain();
                            nextMsg.what = MSG_TIP_TEXT;
                            sendMessageDelayed(nextMsg, 250);

                            //                            if (bodyRectView.wordNum == bodyRectView.tipText.length()) {
                            //                                bodyRectView.startBtnTimerAnim();
                            //                            }
                        }
                        break;
                    case MSG_TIMER_COUNT:
                        removeMessages(MSG_TIMER_COUNT);
                        bodyRectView.count--;
                        bodyRectView.tvCount.setText(String.valueOf(bodyRectView.count));
                        if (bodyRectView.count == 0) {
                            bodyRectView.tvCount.setVisibility(View.INVISIBLE);
                            // go to take pic
                            if (bodyRectView.onTimeCountOverListener != null) {
                                bodyRectView.onTimeCountOverListener.onTimeOver();
                            }
                        } else {
                            bodyRectView.tvCount.setVisibility(View.VISIBLE);
                            Message newMsg = Message.obtain();
                            newMsg.what = MSG_TIMER_COUNT;
                            sendMessageDelayed(newMsg, 1000);
                            bodyRectView.tvCount.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    bodyRectView.tvCount.setVisibility(View.INVISIBLE);
                                }
                            }, 400);
                            SoundUtil.playAsyc(bodyRectView.getContext(), bodyRectView.soundResIds[bodyRectView.count - 1], false);
                        }
                        break;
                    //                    case MSG_PROGRESS:
                    //                        removeMessages(MSG_PROGRESS);
                    //                        if (bodyRectView.progress < 100) {
                    //                            bodyRectView.progress += 2;
                    //                            bodyRectView.progressBar.setProgress(bodyRectView.progress);
                    //                            Message progressMsg = Message.obtain();
                    //                            progressMsg.what = MSG_PROGRESS;
                    //                            sendMessageDelayed(progressMsg, 70);
                    //                        }
                    //                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void init() {
        myHandler = new MyHandler(this);
        View root = inflate(getContext(), R.layout.layout_body_rect_view, this);
        ivStandardRect = root.findViewById(R.id.iv_standard_rect);
        ivKedu = root.findViewById(R.id.iv_kedu);
        panelStandTip = root.findViewById(R.id.panel_stand_tip);
        ivNeck = root.findViewById(R.id.iv_ca_neck);
        ivYaoshen = root.findViewById(R.id.iv_ca_yaoshen);
        ivLegLong = root.findViewById(R.id.iv_ca_leg_long);
        ivSmallLeg = root.findViewById(R.id.iv_ca_small_leg);
        btnStartTimer = root.findViewById(R.id.btn_start_timer);
        tvStandTip = root.findViewById(R.id.tv_stand_tip);
        tvStandTip.setVisibility(View.INVISIBLE);
        //        panelStartTipText = root.findViewById(R.id.panel_start_tip_text);
        panelTimerProgress = root.findViewById(R.id.panel_timer_progress);
        tvCount = root.findViewById(R.id.tv_count);
        //        progressBar = root.findViewById(R.id.progress_timer);
        ivDotLineX = root.findViewById(R.id.iv_dot_line_x);
        ivDotLineY = root.findViewById(R.id.iv_dot_line_y);
        ivDotLineY.setX(0);
        setVisibility(View.GONE);

        postDelayed(new Runnable() {
            @Override
            public void run() {
                startAnim();
            }
        }, 5500);

        //        setOnClickListener(new OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                startAnim();
        //            }
        //        });

        btnStartTimer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!btnStartTimer.isSelected()) {
                    btnStartTimer.setSelected(true);
                    btnStartTimer.clearAnimation();
                    //                    panelStartTipText.setVisibility(View.GONE);
                    panelTimerProgress.setVisibility(View.VISIBLE);
                    Message msg = Message.obtain();
                    // 倒计时
                    msg.what = MSG_TIMER_COUNT;
                    myHandler.sendMessageDelayed(msg, 1000);
                    tvCount.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tvCount.setVisibility(View.INVISIBLE);
                            SoundUtil.playAsyc(getContext(), R.raw.timer_count_bg, false);
                        }
                    }, 400);

                    SoundUtil.playAsyc(getContext(), soundResIds[count - 1], false);
                    // 进度条
                    //                    Message progressMsg = Message.obtain();
                    //                    progressMsg.what = MSG_PROGRESS;
                    //                    myHandler.sendMessageDelayed(progressMsg, 50);
                }
            }
        });
    }

    private void startTimerCount() {
        if (!btnStartTimer.isSelected()) {
            //            myHandler.removeMessages(MSG_PROGRESS);
            myHandler.removeMessages(MSG_TIMER_COUNT);
            btnStartTimer.setSelected(true);
            btnStartTimer.clearAnimation();
            //            panelStartTipText.setVisibility(View.GONE);
            panelTimerProgress.setVisibility(View.VISIBLE);
            Message msg = Message.obtain();
            // 倒计时
            msg.what = MSG_TIMER_COUNT;
            myHandler.sendMessageDelayed(msg, 1000);
            tvCount.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tvCount.setVisibility(View.INVISIBLE);
                    SoundUtil.playAsyc(getContext(), R.raw.timer_count_bg, false);
                }
            }, 400);

            SoundUtil.playAsyc(getContext(), soundResIds[count - 1], false);
            // 进度条
            //            Message progressMsg = Message.obtain();
            //            progressMsg.what = MSG_PROGRESS;
            //            myHandler.sendMessageDelayed(progressMsg, 50);
        }
    }

    // 重新倒计时
    public void resetBtnTimer() {
        count = 5;
        tvCount.setVisibility(View.VISIBLE);
        tvCount.setText(String.valueOf(count));
        btnStartTimer.clearAnimation();
        btnStartTimer.setSelected(false);
        //        panelStartTipText.setVisibility(View.VISIBLE);
        panelTimerProgress.setVisibility(View.GONE);
        //        progress = 0;
        //        progressBar.setProgress(progress);
        startBtnTimerAnim();
    }

    private void startAnim() {
        wordNum = 1;
        count = 5;
        //        progress = 0;
        //        progressBar.setProgress(progress);
        //        .setSelected(false);
        //        panelStartTipText.setVisibility(View.VISIBLE);
        panelTimerProgress.setVisibility(View.GONE);
        tvCount.setVisibility(View.VISIBLE);
        tvCount.setText(String.valueOf(count));

        setVisibility(View.VISIBLE);
        ivKedu.setVisibility(View.INVISIBLE);
        panelStandTip.setVisibility(View.INVISIBLE);
        btnStartTimer.setVisibility(View.INVISIBLE);

        ivNeck.setAlpha(0f);
        ivYaoshen.setAlpha(0f);
        ivLegLong.setAlpha(0f);
        ivSmallLeg.setAlpha(0f);
        startStandRectAnim();
    }

    private void startStandRectAnim() {
        ObjectAnimator scaleUpX = ObjectAnimator.ofFloat(ivStandardRect, "scaleX", 0.3f, 1);
        ObjectAnimator scaleUpY = ObjectAnimator.ofFloat(ivStandardRect, "scaleY", 0.3f, 1);
        scaleUpX.setDuration(500);
        scaleUpY.setDuration(500);
        BounceInterpolator interpolator = new BounceInterpolator();
        scaleUpX.setInterpolator(interpolator);
        scaleUpY.setInterpolator(interpolator);
        AnimatorSet anim = new AnimatorSet();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                startKeduAnim();
                startStandTipAnim();
                //                startBodyPartAnim(ivNeck, 800);
                //                startBodyPartAnim(ivYaoshen, 1200);
                //                startBodyPartAnim(ivLegLong, 1600);
                //                startBodyPartAnim(ivSmallLeg, 2000);
            }
        });
        anim.playTogether(scaleUpX, scaleUpY);
        anim.start();
    }

    private void startKeduAnim() {
        ivKedu.setVisibility(View.VISIBLE);
        ObjectAnimator move = ObjectAnimator.ofFloat(ivKedu, "translationX", 50, 0);
        move.setDuration(500);
        ObjectAnimator fadeIn = ObjectAnimator.ofFloat(ivKedu, "alpha", 0.3f, 1);
        fadeIn.setDuration(500);
        AnimatorSet anim = new AnimatorSet();
        anim.playTogether(move, fadeIn);
        anim.start();
    }

    private void startStandTipAnim() {
        panelStandTip.setVisibility(View.VISIBLE);
        ObjectAnimator move = ObjectAnimator.ofFloat(panelStandTip, "translationY", 50, 0);
        move.setDuration(500);
        ObjectAnimator fadeIn = ObjectAnimator.ofFloat(panelStandTip, "alpha", 0.3f, 1);
        fadeIn.setDuration(500);
        AnimatorSet anim = new AnimatorSet();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                tvStandTip.setVisibility(View.VISIBLE);
                Message msg = Message.obtain();
                msg.what = MSG_TIP_TEXT;
                myHandler.sendMessageDelayed(msg, 400);
            }
        });
        anim.playTogether(move, fadeIn);
        anim.start();
    }

    private void startBodyPartAnim(View view, int delay) {
        ObjectAnimator move = ObjectAnimator.ofFloat(view, "translationX", -270, 0);
        move.setDuration(510);
        ObjectAnimator fadeIn = ObjectAnimator.ofFloat(view, "alpha", 0.3f, 1);
        fadeIn.setDuration(500);
        ObjectAnimator scaleUpX = ObjectAnimator.ofFloat(view, "scaleX", 0.6f, 1);
        ObjectAnimator scaleUpY = ObjectAnimator.ofFloat(view, "scaleY", 0.6f, 1);
        scaleUpX.setDuration(500);
        scaleUpY.setDuration(500);

        move.setInterpolator(new BounceInterpolator());
        AnimatorSet anim = new AnimatorSet();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                SoundUtil.playAsyc(getContext(), R.raw.shot_effect, false);
                //                SoundUtil.play(getContext(), R.raw.shot_effect);
            }
        });
        anim.playTogether(move, fadeIn, scaleUpX, scaleUpY);
        anim.setStartDelay(delay);
        anim.start();
    }

    // 启动拍照按钮动画
    public void startBtnTimerAnim() {
        btnStartTimer.setVisibility(View.VISIBLE);
        ObjectAnimator scaleUpX = ObjectAnimator.ofFloat(btnStartTimer, "scaleX", 0, 1f);
        ObjectAnimator scaleUpY = ObjectAnimator.ofFloat(btnStartTimer, "scaleY", 0, 1f);
        OvershootInterpolator interpolator = new OvershootInterpolator(1.3f);
        scaleUpX.setInterpolator(interpolator);
        scaleUpY.setInterpolator(interpolator);
        AnimatorSet anim = new AnimatorSet();
        anim.setDuration(600);
        anim.playTogether(scaleUpX, scaleUpY);
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {

                ScaleAnimation scale = new ScaleAnimation(1, 1.1f, 1, 1.1f
                        , Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                scale.setDuration(300);
                scale.setRepeatMode(ScaleAnimation.REVERSE);
                scale.setRepeatCount(ScaleAnimation.INFINITE);
                btnStartTimer.startAnimation(scale);

                // 倒计时开始
                startTimerCount();
            }
        });
        anim.start();
    }

    private AnimatorSet hideBtnTimeAnimator;

    public void hideBtnTimerAnim() {
        if (hideBtnTimeAnimator == null) {
            ObjectAnimator scaleX = ObjectAnimator.ofFloat(btnStartTimer, "scaleX", 1, 0);
            ObjectAnimator scaleY = ObjectAnimator.ofFloat(btnStartTimer, "scaleY", 1, 0);
            scaleX.setDuration(500);
            scaleY.setDuration(500);
            BounceInterpolator interpolator = new BounceInterpolator();
            scaleX.setInterpolator(interpolator);
            scaleY.setInterpolator(interpolator);
            hideBtnTimeAnimator = new AnimatorSet();
            hideBtnTimeAnimator.playTogether(scaleX, scaleY);
        }
        hideBtnTimeAnimator.start();

        // reset data
        count = 5;
        //        myHandler.removeMessages(MSG_PROGRESS);
        myHandler.removeMessages(MSG_TIMER_COUNT);
    }

    public void setLineXY(float x, float y) {
        ivDotLineX.setY(y);
        ivDotLineY.setX(x);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (myHandler != null) {
            myHandler.removeCallbacksAndMessages(null);
        }
    }
}
